﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.Caching;
using System.Web.Caching;

namespace SalesSys.Comm.Utility
{
    public interface ICache<TKey, TValue>//:IDisposable
    {
          TValue this[TKey key] { get; set; }
        void Remove(TKey key);
    }

    public class MemoryCacheEx:MemoryCache,ICache<string , object>
    {
        public MemoryCacheEx(string name, NameValueCollection config = null):base(name,config)
        { 
        }
        public void Set(string key, object value, TimeSpan slidingExpiration)
        {
           
             Set(key, value, CreatePolicy(slidingExpiration, null));
        }
       
        public void Remove(string key)
        {
            base.Remove(key);
        }
        private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
        {
            var policy = new CacheItemPolicy();

            if (absoluteExpiration.HasValue)
            {
                policy.AbsoluteExpiration = absoluteExpiration.Value;
            }
            else if (slidingExpiration.HasValue)
            {
                policy.SlidingExpiration = slidingExpiration.Value;
            }
            return policy;
        }
    } 

    public class DictionaryCache<TKey, TValue> : ICache<TKey, TValue>
    {
        IDictionary<TKey, TValue> dic = null;
        public DictionaryCache(IDictionary<TKey, TValue> dicColl=null)
        {
            dic = dicColl??new Dictionary<TKey,TValue>();
        }

        public TValue this[TKey key]
        {
            get
            {
                return dic[key];
            }
            set
            {
                dic[key] = value;
            }
        }

        public void Remove(TKey key)
        {
            dic.Remove(key);
        }
    }


    public class WebCache<TKey, TValue> : ICache<TKey, TValue>
    {
        Cache cache = null;

        public WebCache(Cache internalCache=null)
        {
            cache =internalCache?? new Cache();
        }

        public TValue this[TKey key]
        {
            get
            {
                return (TValue)cache[key.ToString()];
            }
            set
            {
                cache[key.ToString()] = value;
            }
        }
        public void Remove(TKey key)
        {
             cache.Remove(key.ToString());
        }
    }
}
